package cc.rengu.oltp.utility.util;

import cc.rengu.utility.cache.UnifiedCache;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Set;

/**
 * 缓存操作工具类
 * Created by 王成 on 2017/11/13.
 */
public class CacheUtil {

    /**
     * 将XML配置文件加载到缓存
     * 缓存KEY：XML二级节点名
     * 缓存值：XML所有三级节点对应的实体类
     *
     * @param cacheName      缓存名
     * @param configFileName 配置文件名
     * @param className      实体类名
     * @return 0-成功，其它-失败
     * @throws Exception 异常
     */
    public static int loadShareCacheConfig(String cacheName, String configFileName, String className) throws Exception {
        int iReturnCode = 0;
        Map<String, String> shareCacheMap = XmlConfigUtil.loadXmlConfigInfo(configFileName);
        if (null != shareCacheMap) {
            /* 清空缓存 */
            UnifiedCache.clear(cacheName);
            /* 将配置参数加载到缓存 */
            for (Map.Entry<String, String> entry : shareCacheMap.entrySet()) {
                Object object = parseJsonStringToObject(entry.getValue().trim(), className);
                iReturnCode = UnifiedCache.set(cacheName, entry.getKey().trim(), object);
                if (0 != iReturnCode) {
                    return iReturnCode;
                }
            }
        }
        return iReturnCode;
    }

    /**
     * 将JSON数组转换成实体类
     *
     * @param jsonString JSON数组字符串
     * @param className  实体类名
     * @return 实体类
     * @throws Exception 异常
     */
    private static Object parseJsonStringToObject(String jsonString, String className) throws Exception {
        Class clazz = Class.forName(className);
        Object object = clazz.newInstance();
        Field[] fields = object.getClass().getDeclaredFields();

        JSONArray jsonArray = JSONArray.parseArray(jsonString);
        for (int k = 0; k < jsonArray.size(); k++) {
            JSONObject jsonObject = jsonArray.getJSONObject(k);
            Set<String> keySet = jsonObject.keySet();
            for (String jsonKey : keySet) {
                for (Field field : fields) {
                    if (jsonKey.equalsIgnoreCase(field.getName())) {
                        field.setAccessible(true);
                        String methodName = "set" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
                        Method method = object.getClass().getDeclaredMethod(methodName, field.getType());
                        method.invoke(object, jsonObject.getString(jsonKey));
                    }
                }
            }
        }
        return object;
    }
}
